export interface ExportCsvDataType {
  columns: Array<{
    header: string;
    key: string;
  }>;
  data: any[];
}
export const exportCsv = (data: ExportCsvDataType, name?: string) => {
  const csvHeader = data.columns.map((h) => h.header).join(",") + "\n";
  const csvData = data.data
    .map((item) => data.columns.map((h) => item[h.key]).join(","))
    .join("\n");
  const csvContent = csvHeader + csvData;
  const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
  const url = URL.createObjectURL(blob);
  const csvName = `${name || "table"}.csv`;
  downloadFile(url, csvName);
};

export function downloadMarkdown(markdownContent: string, fileName?: string) {
  const blob = new Blob([markdownContent], { type: "text/markdown" });
  const url = URL.createObjectURL(blob);
  downloadFile(url, fileName);
}

export function downloadFile(url: string, filename?: string) {
  const link = document.createElement("a");
  link.href = url;
  link.download = filename || "";
  if (window.MouseEvent) {
    const clickEvent = new MouseEvent("click", {
      view: window,
      bubbles: true,
      cancelable: true,
    });
    link.dispatchEvent(clickEvent);
  } else {
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}

export function cleanFileName(fileName: string, replaceTag?: string) {
  const lastDotIndex = fileName.lastIndexOf(".");
  if (lastDotIndex === -1) {
    return fileName;
  }
  const baseName = fileName.slice(0, lastDotIndex);
  const extension = fileName.slice(lastDotIndex);
  const cleanedBaseName = baseName.replace(/\./g, replaceTag ?? "_");
  return cleanedBaseName + extension;
}

export async function checkFileExists(url: string) {
  try {
    const response = await fetch(url, { method: "HEAD" });
    if (response.ok) {
      console.log(`${url} exists.`);
      return true;
    } else {
      console.log(`${url} does not exist. Status: ${response.status}`);
      return false;
    }
  } catch (error) {
    console.error("Error:", error);
    return false;
  }
}

export function encodeFilename(path: string) {
  const hasLeadingSlash = path.startsWith("/");
  const parts = path.split("/");
  const filename = parts[parts.length - 1];
  const encodedFilename = encodeURI(filename);
  parts[parts.length - 1] = encodedFilename;
  const encodedPath = parts.join("/");
  return hasLeadingSlash ? "/" + encodedPath : encodedPath;
}

export function customEncode(str: string) {
  const specialChars = /[%!'()*]/g;
  return str.replace(specialChars, (char) => {
    return "%" + char.charCodeAt(0).toString(16).toUpperCase();
  });
}

export const validateFileName = (filename: string): boolean => {
  // 基础字符集校验（允许中文、字母、数字、安全符号、空格和中英文括号）
  const baseCheck = /^[\w\u4e00-\u9fa5~.\s()（）/-]+$/iu.test(filename);
  // 额外禁止的特殊字符（即使包含中文也需要过滤）
  const extraInvalidChars = ["\\", "*", "?", '"', "<", ">", "|", ":"];
  const hasExtraInvalid = extraInvalidChars.some((char) =>
    filename.includes(char)
  );
  // 字节长度校验（UTF-8编码）
  const encoder = new TextEncoder();
  const isLengthValid = encoder.encode(filename).length <= 1024;
  return baseCheck && !hasExtraInvalid && isLengthValid;
};

export function readBlobAsText(blob: Blob): Promise<string> {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    fileReader.onload = () => {
      resolve(fileReader.result as string);
    };
    fileReader.onerror = () => {
      reject(new Error("Failed to read Blob"));
    };
    fileReader.readAsText(blob);
  });
}

export async function readJsonBlob(data: Blob) {
  const text = await readBlobAsText(data);
  const jsonData = JSON.parse(text);
  return jsonData;
}
